package io.xiaojl.xj2ee.common.kit.http;

import java.io.IOException;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.xiaojl.xj2ee.common.kit.json.JsonKit;

/**
 * <p>Title: HttpKit</p>  
 *
 * <p>Description: Http Client 工具类[支持http和https协议]</p>  
 *
 * @author jilong.xiao  
 * @date 2018年5月23日
 */
public class HttpKit {
	private static final Logger log = LoggerFactory.getLogger(HttpKit.class);
	private static PoolingHttpClientConnectionManager connMgr;  
	private static RequestConfig requestConfig;
	private static final int MAX_TIMEOUT = 7000; //超时
	static {  
        // 设置连接池  
        connMgr = new PoolingHttpClientConnectionManager();  
        // 设置连接池大小  
        connMgr.setMaxTotal(100);  
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());  
        RequestConfig.Builder configBuilder = RequestConfig.custom();  
        // 设置连接超时  
        configBuilder.setConnectTimeout(MAX_TIMEOUT);  
        // 设置读取超时  
        configBuilder.setSocketTimeout(MAX_TIMEOUT);  
        // 设置从连接池获取连接实例的超时  
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);  
  
        requestConfig = configBuilder.build();  
    }
	/** 
     * 创建SSL安全连接 
     */  
    private static SSLConnectionSocketFactory createSSLConnSocketFactory() {  
        SSLConnectionSocketFactory sslsf = null;  
        try {  
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {  
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
                    return true;  
                }
            }).build();  
            sslsf = new SSLConnectionSocketFactory(sslContext);  
        } catch (GeneralSecurityException e) {  
        	log.error("创建SSL安全连接出现异常：",e);
        }  
        return sslsf;  
    }  
	public static String doGet(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = null ;
		if(url.startsWith("https")){
			httpclient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())  
                    .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); 
		}else{
			httpclient = HttpClients.createDefault();
		}
		
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			// 执行请求
			response = httpclient.execute(httpGet);
			
			if(log.isDebugEnabled()){
				StringBuilder buffer = new StringBuilder();
				buffer.append("\r\n");
				buffer.append("====================================================").append("\r\n");
				buffer.append("\t请求方式：GET").append("\r\n");
				buffer.append("\t请求地址：").append(url).append("\r\n");
				buffer.append("\t请求参数：").append(JsonKit.toJson(param)).append("\r\n");
				buffer.append("\t响应状态：").append(response.getStatusLine().getStatusCode()).append("\r\n");
				buffer.append("\t响应结果：").append(EntityUtils.toString(response.getEntity(), "UTF-8")).append("\r\n");
				buffer.append("====================================================");
				log.debug(buffer.toString());
			}
			
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			log.error("HTTP GET请求出现异常", e);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
			}
		}
		return resultString;
	}

	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doPost(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = null ;
		if(url.startsWith("https")){
			httpclient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())  
                    .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); 
		}else{
			httpclient = HttpClients.createDefault();
		}
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpclient.execute(httpPost);
			
			if(log.isDebugEnabled()){
				StringBuilder buffer = new StringBuilder();
				buffer.append("\r\n");
				buffer.append("====================================================").append("\r\n");
				buffer.append("\t请求方式：GET").append("\r\n");
				buffer.append("\t请求地址：").append(url).append("\r\n");
				buffer.append("\t请求参数：").append(JsonKit.toJson(param)).append("\r\n");
				buffer.append("\t响应状态：").append(response.getStatusLine().getStatusCode()).append("\r\n");
				buffer.append("\t响应结果：").append(EntityUtils.toString(response.getEntity(), "UTF-8")).append("\r\n");
				buffer.append("====================================================");
				log.debug(buffer.toString());
			}
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			log.error("HTTP POST请求出现异常", e);
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doPost(String url) {
		return doPost(url, null);
	}

	public static String doPostJson(String url, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = null ;
		if(url.startsWith("https")){
			httpclient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())  
                    .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); 
		}else{
			httpclient = HttpClients.createDefault();
		}
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpclient.execute(httpPost);
			if(log.isDebugEnabled()){
				StringBuilder buffer = new StringBuilder();
				buffer.append("\r\n");
				buffer.append("====================================================").append("\r\n");
				buffer.append("\t请求方式：GET").append("\r\n");
				buffer.append("\t请求地址：").append(url).append("\r\n");
				buffer.append("\t请求参数：").append(json).append("\r\n");
				buffer.append("\t响应状态：").append(response.getStatusLine().getStatusCode()).append("\r\n");
				buffer.append("\t响应结果：").append(EntityUtils.toString(response.getEntity(), "UTF-8")).append("\r\n");
				buffer.append("====================================================");
				log.debug(buffer.toString());
			}
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "utf-8");
			}
			
		} catch (Exception e) {
			log.error("HTTP POST(JSON)请求出现异常", e);
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}
}
